package com.furnitur.modules.admin.controller.auth;

import com.furnitur.common.api.CommonResult;
import com.furnitur.core.entity.user.User;
import com.furnitur.modules.admin.dto.auth.LoginDTO;
import com.furnitur.modules.admin.dto.auth.RegisterDTO;
import com.furnitur.core.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public CommonResult<User> register(@Valid @RequestBody RegisterDTO registerDTO) {
        User user = userService.register(registerDTO);
        return CommonResult.success(user);
    }

    @PostMapping("/login")
    public CommonResult<Map<String, Object>> login(@Valid @RequestBody LoginDTO loginDTO) {
        try {
            String token = userService.login(loginDTO);
            User user = userService.getUserByUsername(loginDTO.getUsername());
            
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("tokenHead", "Bearer ");
            result.put("roles", new String[]{"ROLE_" + user.getRoleId()});
            result.put("userId", user.getId());
            result.put("username", user.getUsername());
            
            return CommonResult.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("登录失败: " + e.getMessage());
        }
    }

    @GetMapping("/info")
    public CommonResult<Map<String, Object>> getInfo() {
        try {
            User currentUser = userService.getCurrentUser();
            if (currentUser == null || currentUser.getRoleId() == null) {
                return CommonResult.failed("获取用户信息失败");
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("name", currentUser.getUsername());
            data.put("avatar", "https://example.com/default-avatar.png");
            data.put("roles", new String[]{"ROLE_" + currentUser.getRoleId()});
            data.put("userId", currentUser.getId());
            data.put("username", currentUser.getUsername());
            
            return CommonResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("获取用户信息失败: " + e.getMessage());
        }
    }

    @PostMapping("/logout")
    public CommonResult<String> logout() {
        return CommonResult.success("退出成功");
    }
} 